package com.damie.utils;

import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class Spring2Date implements Converter<String, Date> {

    /**
     * 使用simpleDataFormat
     *
     * @param source
     * @return
     */
    @Override
    public Date convert(String source) {
        System.out.println("工具类==》"+source);
        if (StringUtils.isEmpty(source)) {
            throw new RuntimeException("参数为空");
        } else {
            String pattern1 = "[0-9]{4}-[0-9]{2}-[0-9]{2}";
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String pattern2 = "[0-9]{4}/[0-9]{2}/[0-9]{2}";
            SimpleDateFormat format2 = new SimpleDateFormat("yyyy/MM/dd");
            try {
                if (source.matches(pattern1)) {

                    return format.parse(source);
                }
                if (source.matches(pattern2)) {
                    return format2.parse(source);
                }
            }catch(ParseException e){
                e.printStackTrace();
            }
        }
        return null;
    }
}
